Skip to main content

Count Unique Characters of All Substrings of a Given String

Question

Given a string, write an algorithm to count the number of unique characters in all substrings of the given string.

Example 1
None

Solution

all//Count Unique Characters of All Substrings of a Given String.py


def countUniqueChars(string):
unique_chars = set()
for i in range(len(string)):
for j in range(i+1, len(string)+1):
for char in string[i:j]:
unique_chars.add(char)
return len(unique_chars)

# Driver code
string = "abab"
print(countUniqueChars(string))